package org.yinxianren.java.test.thread;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Calculator implements Runnable{

    private int number;
    public Calculator(int number) {
        this.number=number;
    }
    public void run() {
        for (int i=1; i<=10; i++){
            System.out.printf("%s: %d * %d = %d \n",Thread.currentThread().getName(),number,i,i*number);
        }
    }
}

/**
 *  案例一
 */
class MainFunction{
    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            Thread  thread = new Thread(new Calculator(i));
            thread.start();
        }

    }
}

/**
 *  案例二
 */
class MainFunctionTwo{
    public static void main(String[] args) throws IOException {
        Thread threads[]=new Thread[10];
        Thread.State[] status = new Thread.State[10];

        for (int i=0; i<10; i++){
            threads[i]=new Thread(new Calculator(i));
            if ((i%2)==0){
                threads[i].setPriority(Thread.MAX_PRIORITY);
            } else {
                threads[i].setPriority(Thread.MIN_PRIORITY);
            }
            threads[i].setName("Thread "+i);
        }

        FileWriter file = new FileWriter(".\\log.txt");
        PrintWriter pw = new PrintWriter(file);


        for (int i=0; i<10; i++){
            pw.println("Main : Status of Thread "+i+" : " +threads[i].getState());
            status[i]=threads[i].getState();
        }

        pw.flush();

        for (int i=0; i<10; i++){
            threads[i].start();
        }

//直到这10个线程执行结束，我们会一直检查它们的状态。如果发现它的状态改变，就把状态记入文本。
        boolean finish=false;
        while (!finish) {
            for (int i=0; i<10; i++){
                if (threads[i].getState()!=status[i]) {
                    writeThreadInfo(pw, threads[i],status[i]);
                    status[i]=threads[i].getState();
                }
            }
            finish=true;
            for (int i=0; i<10; i++){
                // 只有十个线程全部结束，finish && (threads[i].getState() == Thread.State.TERMINATED) 才有等于true
                finish = finish && (threads[i].getState() == Thread.State.TERMINATED);
            }
        }

        pw.close();
    }
//实现一个方法 writeThreadInfo()，这个方法写线程的 ID, name, priority, old status, 和 new status。
    private static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State state) {
        pw.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
        pw.printf("Main : Priority: %d\n",thread.getPriority());
        pw.printf("Main : Old State: %s\n",state);
        pw.printf("Main : New State: %s\n",thread.getState());
        pw.printf("Main : ************************************\n");
        pw.flush();
    }

}
